package com.macro.mall.tiny.modules.pms.controller;


import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.common.api.ResultCode;
import com.macro.mall.tiny.modules.pms.model.PmsCategory;
import com.macro.mall.tiny.modules.pms.model.PmsCoolTool;
import com.macro.mall.tiny.modules.pms.model.PmsCoolToolBrand;
import com.macro.mall.tiny.modules.pms.model.PmsCoolToolUpdateGroupDTO;
import com.macro.mall.tiny.modules.pms.service.PmsCategoryService;
import com.macro.mall.tiny.modules.pms.service.PmsCoolToolBrandService;
import com.macro.mall.tiny.modules.pms.service.PmsCoolToolService;
import com.macro.mall.tiny.modules.ums.model.UmsMember;
import com.macro.mall.tiny.security.util.MemberContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.parameters.P;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tyrone
 * @since 2024-10-09
 */
@RestController
@RequestMapping("/pms/pmsCoolTool")
@Api(tags = "PmsCoolToolController")
@Tag(name = "PmsCoolToolController", description = "制冷工具箱管理")
public class PmsCoolToolController {
    @Autowired
    private PmsCoolToolService pmsCoolToolService;
    @Autowired
    private PmsCategoryService pmsCategoryService;

    @Autowired
    private PmsCoolToolBrandService pmsCoolToolBrandService;

    @ApiOperation(value = "前台获取所有制冷工具箱的分类")
    @GetMapping("/categories")
    public CommonResult<List<PmsCoolToolBrand>> getCategories() {
        return CommonResult.success(pmsCoolToolBrandService.list());
    }

    @ApiOperation(value = "后台添加制冷工具箱的分类")
    @PostMapping("/category")
    public CommonResult<PmsCoolToolBrand> addCategory(@RequestBody PmsCoolToolBrand pmsCoolToolBrand) {
        pmsCoolToolBrandService.save(pmsCoolToolBrand);
        return CommonResult.success(pmsCoolToolBrand);
    }

    @ApiOperation(value = "后台删除制冷工具箱的分类")
    @DeleteMapping("/category/{id}")
    public CommonResult<Void> deleteCategory(@PathVariable Integer id) {
        pmsCoolToolBrandService.removeById(id);
        return CommonResult.success(null);
    }

    @ApiOperation(value = "后台批量删除工具箱的分类")
    @DeleteMapping("/category")
    public CommonResult<Void> deleteCategory(@RequestBody List<Integer> ids) {
        pmsCoolToolBrandService.removeByIds(ids);
        return CommonResult.success(null);
    }


    @ApiOperation(value = "后台更新制冷工具箱的分类")
    @PutMapping("/category")
    public CommonResult<PmsCoolToolBrand> updateCategory(@RequestBody PmsCoolToolBrand pmsCoolToolBrand) {
        pmsCoolToolBrandService.updateById(pmsCoolToolBrand);
        return CommonResult.success(pmsCoolToolBrand);
    }

    @ApiOperation("后台分页获取制冷工具箱的分类")
    @GetMapping("/category/page")
    public CommonResult<IPage<PmsCoolToolBrand>> listCategory(@RequestParam(required = false) Integer id,@RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) String name) {
        QueryWrapper<PmsCoolToolBrand> query = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(name)) {
            query.like("name", name);
        }
        if (!ObjectUtils.isEmpty(id)) {
            query.eq("id", id);
        }
        return CommonResult.success(pmsCoolToolBrandService.page(new Page<>(page, size, Boolean.TRUE), query));
    }

    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("前台万能分页查询")
    @PostMapping("/page")
    public CommonResult<IPage<PmsCoolTool>> page(@RequestBody PmsCoolTool pmsCoolTool) {
        QueryWrapper<PmsCoolTool> query = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(pmsCoolTool.getName())) {
            query.like("name", pmsCoolTool.getName());
            UmsMember member = MemberContext.getMember();
            if (member!=null){
                String key ="PmsCoolTool:"+member.getId();
                // 删除重复记录
                redisTemplate.opsForList().remove(key, 0, pmsCoolTool.getName());
                // 添加到列表头部
                redisTemplate.opsForList().leftPush(key, pmsCoolTool.getName());
                // 限制列表长度
                redisTemplate.opsForList().trim(key, 0, 9);

            }
        }
        if (!ObjectUtils.isEmpty(pmsCoolTool.getCategoryId())) {
            query.eq("category_id", pmsCoolTool.getCategoryId());
        }
        query.orderByAsc("sort");
        query.orderByDesc("id");
        query.apply("icon = url");
        query.groupBy("name");

        Page<PmsCoolTool> page = pmsCoolToolService.page(new Page<>(pmsCoolTool.getPage(), pmsCoolTool.getSize(), Boolean.TRUE), query);
        page.getRecords().forEach(e -> e.setUrl(null));
        return CommonResult.success(page);
    }

    @ApiOperation("后台万能分页查询")
    @PostMapping("/admin/page")
    public CommonResult<IPage<PmsCoolTool>> listAll(@RequestBody PmsCoolToolDTO dto) {
        QueryWrapper<PmsCoolTool> query = new QueryWrapper<>();
        if (dto.getId() != null) {
            query.eq("id", dto.getId());
        }
        if (!ObjectUtils.isEmpty(dto.getShowStatus())) {
            query.eq("show_status", dto.getShowStatus());
        }

        if (!ObjectUtils.isEmpty(dto.getName())) {
            query.like("name", dto.getName());
        }
        if (!ObjectUtils.isEmpty(dto.getCategoryId())) {
            query.eq("category_id", dto.getCategoryId());
        }
        if (dto.getEnabledGroupByName()) {
            query.apply("icon = url");
            query.groupBy("name");
        }


        query.orderByDesc("id");
        Map<Integer, String> nameMap = pmsCoolToolBrandService.list().stream().collect(Collectors.toMap(PmsCoolToolBrand::getId, PmsCoolToolBrand::getName));
        Page<PmsCoolTool> page = pmsCoolToolService.page(new Page<>(dto.getPage(), dto.getSize(), Boolean.TRUE), query);
        page.getRecords().forEach(e->e.setCategoryName(nameMap.get(e.getCategoryId())));
        return CommonResult.success(page);
    }

    @ApiOperation("获取制冷工具箱详情")
    @GetMapping("/detail")
    public CommonResult<List<PmsCoolTool>> getDetail(@ApiParam("文件名字") @RequestParam String name,@RequestParam(required = false) Integer type) {
        UmsMember member = MemberContext.getMember();
        if (member == null) {
            return CommonResult.failed(ResultCode.UNAUTHORIZED);
        }
        if (type != null && type == 1) {
            return CommonResult.success(pmsCoolToolService.list(new QueryWrapper<PmsCoolTool>().eq("name", name).eq("type",1)));
        }
        List<PmsCoolTool> list = pmsCoolToolService.list(new QueryWrapper<PmsCoolTool>().eq("name", name).orderByAsc("url"));
        int index = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getUrl().equals(list.get(i).getIcon())) {
                index = i;
                break;
            }
            if (list.get(i).getShowStatus() == 1 && member.getVip() == 0) {
                return CommonResult.failed(ResultCode.NEED_VIP);
            }
        }
        PmsCoolTool first = list.remove(index);
//        if (index !=0){
//
//            list.add(0, first);
//        }
        return CommonResult.success(list);
    }

    @ApiOperation("后台获取制冷工具箱详情")
    @GetMapping("/detailForAdmin")
    public CommonResult<List<PmsCoolTool>> getDetailAdmin(@ApiParam("文件名字") @RequestParam String name) {
        List<PmsCoolTool> list = pmsCoolToolService.list(new QueryWrapper<PmsCoolTool>().eq("name", name).orderByAsc("url"));
        Map<Integer, String> nameMap = pmsCoolToolBrandService.list().stream().collect(Collectors.toMap(PmsCoolToolBrand::getId, PmsCoolToolBrand::getName));
        int index = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getUrl().equals(list.get(i).getIcon())) {
                index = i;
                break;
            }
        }
        list.forEach(e -> e.setCategoryName(nameMap.get(e.getCategoryId())));
        PmsCoolTool first = list.remove(index);
//        if (index !=0){
//
//            list.add(0, first);
//        }
        return CommonResult.success(list);
    }

    @ApiOperation("后台添加制冷工具箱")
    @PostMapping("/add")
    public CommonResult<Void> add(@RequestBody PmsCoolTool pmsCoolTool) {
        List<PmsCoolTool> coolTools = new ArrayList<>();
        if (pmsCoolTool.getType() == 1){
            pmsCoolTool.setUrl(pmsCoolTool.getIcon());
            coolTools.add(pmsCoolTool);
            pmsCoolToolService.saveCoolTool(coolTools);
            return CommonResult.success(null);
        }
        for (String url : pmsCoolTool.getUrls()) {
            PmsCoolTool coolTool = new PmsCoolTool();
            coolTool.setCategoryId(pmsCoolTool.getCategoryId());
            coolTool.setName(pmsCoolTool.getName());
            coolTool.setUrl(url);
            coolTool.setIcon(pmsCoolTool.getIcon());
            coolTools.add(coolTool);
        }
        pmsCoolToolService.saveCoolTool(coolTools);
        return CommonResult.success(null);
    }

    @ApiOperation("后台批量删除制冷工具箱")
    @DeleteMapping("/delete")
    public CommonResult<Void> delete(@RequestBody List<Integer> ids) {
        pmsCoolToolService.removeByIds(ids);
        return CommonResult.success(null);
    }

    @ApiOperation("后台外层批量根据名字全匹配删除 对于list中的每一项必须传入name 和categoryId ")
    @DeleteMapping("/deleteByName")
    public CommonResult<Void> deleteByName(@RequestBody List<PmsCoolTool> coolTools) {
        for (PmsCoolTool tool : coolTools) {
            if (StringUtils.isNotEmpty(tool.getName()) && tool.getCategoryId()!=null){
                pmsCoolToolService.remove(new QueryWrapper<PmsCoolTool>().eq("name", tool.getName()).eq("category_id",tool.getCategoryId()));
            }
        }
        return CommonResult.success(null);
    }

    @ApiOperation("后台外层批量根据category和name匹配 进行更新")
    @PutMapping("/updateGroup")
    public CommonResult<Void> updateGroup(@RequestBody PmsCoolToolUpdateGroupDTO dto) {
        PmsCoolTool byId = pmsCoolToolService.getById(dto.getId());
        PmsCoolToolUpdateGroupDTO request = new PmsCoolToolUpdateGroupDTO();
        request.setUpdatedName(dto.getName());
        request.setUpdatedCategoryId(dto.getCategoryId());
        request.setName(byId.getName());
        request.setCategoryId(byId.getCategoryId());
        request.setShowStatus(dto.getShowStatus());

        if (ObjectUtils.isEmpty(request.getName()) || ObjectUtils.isEmpty(request.getCategoryId())) {
            return CommonResult.failed(ResultCode.VALIDATE_FAILED);
        }
        pmsCoolToolService.updateGroup(request);
        return CommonResult.success(null);
    }

    @ApiOperation("后台更新制冷工具箱")
    @PutMapping("/update")
    public CommonResult<Void> update(@RequestBody PmsCoolTool pmsCoolTool) {
        if (pmsCoolTool.getType() == 1){
            pmsCoolTool.setUrl(pmsCoolTool.getIcon());
        }
        pmsCoolToolService.updateById(pmsCoolTool);
        return CommonResult.success(null);
    }



    @Data
    public static class PmsCoolToolDTO {
        @ApiModelProperty("主键id")
        private Integer id;

        @ApiModelProperty("分类id")
        private Integer categoryId;

        @ApiModelProperty("工具名称")
        private String name;

        @ApiModelProperty("封面")
        private String icon;

        @ApiModelProperty("文件地址")
        private List<String> urls;

        @ApiModelProperty("展示状态 0非vip 1vip")
        private Integer showStatus;


        @ApiModelProperty("分页参数")
        private Integer page = 1;


        @ApiModelProperty("分页参数")
        private Integer size = 10;

        @ApiModelProperty("是否开启根据名字分组")
        private Boolean enabledGroupByName = Boolean.TRUE;
    }

}

